/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
 */

package com.huawei.aiservice.base;

import com.huawei.aiservice.config.GiteeConfig;
import com.huawei.aiservice.constants.GatewayConstant;
import com.huawei.aiservice.entity.vo.InfoVo;
import com.huawei.aiservice.service.UserService;
import com.huawei.aiservice.utils.GiteeAuthUtil;
import com.huawei.aiservice.utils.JwtUtil;
import com.huawei.aiservice.utils.ResponseUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * 码云跳转页
 *
 * @since 2023/10/26 19:22
 */
@Component
@Slf4j
public class GiteeLogin extends Login {
    private static final String AUTH = "&scope=user_info%20issues%20pull_requests";

    /**
     * 状态
     */
    private static final String STATE = "state";

    /**
     * 编码
     */
    private static final String UTF8 = "UTF-8";

    @Autowired
    private GiteeAuthUtil getGiteeAuthUtil;

    @Autowired
    private GiteeConfig giteeConfig;

    @Autowired
    @Qualifier("userServiceThreadPool")
    private ThreadPoolTaskExecutor userServiceThreadPool;

    @Resource
    private UserService userService;



    /**
     * 码云登录方式跳转
     *
     * @param request 请求
     * @param response 响应
     * @return Mono<Void> 过滤器链
     */
    @Override
    public Mono<Void> toLogin(ServerHttpRequest request, ServerHttpResponse response) {
        HashMap<String, String> map = new HashMap<>();
        response.setStatusCode(HttpStatus.OK);
        map.put(GatewayConstant.GitEEConstant.LOGIN_URL, getGiteeLoginUrl(request));
        return ResponseUtil.getUserResponse(response, map);
    }

    @Override
    public Mono<Void> auth(ServerHttpRequest request, ServerHttpResponse response) {
        String code = request.getQueryParams().getFirst("code");
        log.info("gitee code is : {}", code);
        HashMap<String, String> token = getGiteeAuthUtil.getToken(code);
        response.getHeaders()
                .add(GatewayConstant.GitEEConstant.CONTENT_TYPE, GatewayConstant.GitEEConstant.CONTENT_TYPE_VALUE);
        String accessToken = token.get(GatewayConstant.GitEEConstant.ACCESS_TOKEN);
        if (StringUtils.isNotEmpty(accessToken)) {
            log.info("into get info");
            HashMap<String, String> info = GiteeAuthUtil.getInfo(accessToken);
            if (StringUtils.isNotEmpty(info.get(GatewayConstant.PermissionConstant.NAME))) {
                InfoVo infoVo = new InfoVo();
                infoVo.setId(info.get(GatewayConstant.PermissionConstant.ID));
                infoVo.setAccessToken(accessToken);
                infoVo.setName(info.get(GatewayConstant.PermissionConstant.NAME));
                infoVo.setAvatarUrl(info.get(GatewayConstant.PermissionConstant.AVATAR_URL));
                infoVo.setEmail(info.get(GatewayConstant.PermissionConstant.EMAIL));
                infoVo.setLoginName(info.get(GatewayConstant.PermissionConstant.LOGIN));
                // 设置登录类型
                infoVo.setLoginType(GatewayConstant.AuthType.GITEE);
                String oauthToken = JwtUtil.getToken(infoVo);
                response.setStatusCode(HttpStatus.OK);
                ResponseCookie cookie = JwtUtil.getCookie(oauthToken, 8 * 60 * 60);
                log.debug(cookie.toString());
                response.addCookie(cookie);
                response.getHeaders().add(GatewayConstant.GitEEConstant.LOCATION, giteeConfig.getLocation());
                // 异步的保存用户数据或者更改用户数据
                userServiceThreadPool.execute(() -> userService.addUserByChoose(infoVo, 0));
                return response.setComplete();
            }
        }
        HashMap<String, String> map = new HashMap<>();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        map.put(GatewayConstant.GitEEConstant.ERROR_MESSAGE, "accessToken wrong or expired");
        return ResponseUtil.getUserResponse(response, map);
    }

    /**
     * 获取码云的跳转地址
     *
     * @param request 请求
     * @return String 跳转地址
     */
    private String getGiteeLoginUrl(ServerHttpRequest request) {
        log.info("authorizeUrl, clientId, redirectUrl is: {} ,{} ,{}", giteeConfig.getAuthorizeUrl(),
            giteeConfig.getClientId(), giteeConfig.getRedirectUri());
        return String.format(giteeConfig.getAuthorizeUrl(), giteeConfig.getClientId(), giteeConfig.getRedirectUri());
    }

    public static String getDomainValue(ServerHttpRequest request) {
        String result = "";
        if (request == null) {
            return result;
        }
        return request.getQueryParams().getFirst(GatewayConstant.BugConstant.DOMAIN);
    }
}